<template>
  <div class="page-container">
    <div class="page-content">
      <div class="panel-container">
        <div class="panel-content">
          <!--搜索-->
          <SearchForm
            ref="SearchForm"
            style="margin-top: 10px"
            :search-form-arr="searchFormArr"
            @searchParma="searchParma"
          />
        </div>
      </div>
      <!--数据信息-->
      <div class="panel-container no-margin">
        <div
          class="panel-line flex-end"
          style="margin-bottom: 20px"
        >
          <el-button
            type="primary"
            @click="handleAdd"
          >
            + 新增
          </el-button>
        </div>
        <el-table
          ref="table"
          v-loading="dataListLoading"
          stripe
          :data="dataList"
          :header-cell-style="{ background: '#F5F5F5', color: '#000000' }"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            fixed="left"
            width="55"
            :selectable="selectable"
          />
          <el-table-column
            align="center"
            header-align="center"
            label="账号"
            prop="account"
          />
          <el-table-column
            align="center"
            header-align="center"
            label="姓名"
            prop="name"
          />
          <el-table-column
            align="center"
            header-align="center"
            label="业务模块"
            prop="part"
          >
            <template slot-scope="scope">
              {{ getListName(BusinessModuleList, scope.row.part) }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            header-align="center"
            label="角色"
            prop="role_name"
          />
          <el-table-column
            align="center"
            header-align="center"
            label="部门"
            prop="dept_name"
          />
          <el-table-column
            align="center"
            header-align="center"
            label="在职状态"
            prop="rz_sts"
          >
            <template slot-scope="scope">
              {{ getListName(JobStatusList, scope.row.rz_sts) }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            header-align="center"
            label="最后登录时间"
            prop="log_time"
          />
          <el-table-column
            align="center"
            header-align="center"
            label="最后登录IP"
            prop="log_ip"
          />
          <el-table-column
            align="center"
            header-align="center"
            label="登录次数"
            prop="log_count"
          />
          <el-table-column
            align="center"
            header-align="center"
            label="以其身份登录"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleLogin(scope)"
              >
                登录
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            header-align="center"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                :disabled="scope.row.account === 'admin'"
                @click="handleEdit(scope)"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                :class="{ 'button-danger': scope.row.account !== 'admin' }"
                :disabled="scope.row.account === 'admin'"
                @click="handleDelete([scope.row.id])"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          background
          :current-page="pageNumber"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pageTotal"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 20px; text-align: right"
          @current-change="currentChangeHandle"
          @size-change="sizeChangeHandle"
        />
        <!-- <div
          class="panel-line"
          style="margin-top: 20px"
        >
          <el-button
            type="primary"
            :disabled="multipleSelection.length === 0"
            @click="handleOn"
          >
            批量启用
          </el-button>
          <el-button
            type="danger"
            :disabled="multipleSelection.length === 0"
            @click="handleOff"
          >
            批量停用
          </el-button>
          <el-button
            type="danger"
            :disabled="multipleSelection.length === 0"
            @click="handleDeleteMultiple"
          >
            批量删除
          </el-button>
        </div> -->
      </div>
    </div>

    <!--  添加 -->
    <el-drawer
      :title="editModel === 'add' ? '新增员工' : '编辑员工'"
      :visible.sync="showDialogAdd"
      size="50%"
    >
      <DialogAdd
        v-if="showDialogAdd"
        :edit-model="editModel"
        :info="currentItem"
        :role-list="roleList"
        :dept-list="deptList"
        @close="showDialogAdd = false"
        @success="handleAddSuccess"
        @resetPassword="showDialogResetPassword = true"
      />
    </el-drawer>

    <!--  修改密码 -->
    <el-dialog
      title="修改密码"
      :visible.sync="showDialogResetPassword"
      width="40%"
    >
      <DialogResetPassword
        v-if="showDialogResetPassword"
        :id="currentItem.id"
        @close="showDialogResetPassword = false"
        @success="showDialogResetPassword = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  apiUsers,
  apiUserDel,
  apiSysUserSts,
  apiSysRolesList,
  apiSysDeptSelect
} from '@/api/system'
import DialogAdd from './components/DialogAdd.vue'
import DialogResetPassword from './components/DialogResetPassword.vue'
import {
  BusinessModuleList,
  UserLevelList,
  JobStatusList
} from '@/utils/constant'
import { getListName } from '@/utils'

export default {
  name: 'Account',
  components: { DialogAdd, DialogResetPassword },
  data() {
    return {
      JobStatusList,
      BusinessModuleList,
      dataList: [],
      pageNumber: 1,
      pageSize: 10,
      pageTotal: 0,
      dataListLoading: false,
      currentItem: {},
      showDialogAdd: false,
      showDialogResetPassword: false,
      editModel: 'add',
      searchFormArr: [
        {
          fieldName: '账号:',
          type: 'input',
          field: 'account',
          placeholder: '请输入账号'
        },
        {
          fieldName: '姓名:',
          type: 'input',
          field: 'name',
          placeholder: '请输入姓名'
        },
        {
          fieldName: '手机号:',
          type: 'input',
          field: 'phone',
          placeholder: '请输入手机号'
        },
        {
          fieldName: '部门:',
          type: 'cascader',
          field: 'dept_id',
          props: { value: 'id', label: 'name', checkStrictly: true },
          option: []
        },
        {
          fieldName: '角色:',
          type: 'select',
          field: 'role_id',
          option: []
        },
        {
          fieldName: '业务模块:',
          type: 'select',
          field: 'part',
          option: []
        },
        {
          fieldName: '职位等级:',
          type: 'select',
          field: 'level',
          option: []
        },
        {
          fieldName: '入职状态:',
          type: 'select',
          field: 'rz_sts',
          option: []
        }
      ],
      searchParams: {
        account: '',
        name: '',
        phone: '',
        dept_id: '',
        role_id: '',
        part: '',
        level: '',
        rz_sts: ''
      },
      multipleSelection: [],
      deptList: [],
      roleList: []
    }
  },
  activated() {
    this.$refs.table.doLayout()
  },
  mounted() {
    this.init()
  },
  destroyed() {},
  methods: {
    init() {
      this.getSelect()
      this.query = this.$route.query
      const { role_id } = this.query
      if (role_id) {
        this.searchParams.role_id = role_id
      }

      this.$nextTick(() => {
        const setItemList = []
        if (role_id) {
          setItemList.push({ key: 'role_id', value: role_id })
        }
        if (setItemList.length > 0) {
          this.$refs.SearchForm.setItemValue(setItemList)
        } else {
          this.getDataList()
        }
      })
    },
    getSelect() {
      const item1 = this.searchFormArr.find((item) => item.field === 'part')
      item1.option = BusinessModuleList.map((item) => {
        return {
          value: item.id,
          label: item.name
        }
      })
      const item2 = this.searchFormArr.find((item) => item.field === 'level')
      item2.option = UserLevelList.map((item) => {
        return {
          value: item.id,
          label: item.name
        }
      })
      const item3 = this.searchFormArr.find((item) => item.field === 'rz_sts')
      item3.option = JobStatusList.map((item) => {
        return {
          value: item.id,
          label: item.name
        }
      })
      apiSysDeptSelect().then((res) => {
        this.deptList = res.data
        const item = this.searchFormArr.find((item) => item.field === 'dept_id')
        item.option = this.deptList
      })
      apiSysRolesList().then((res) => {
        this.roleList = res.data
        const item = this.searchFormArr.find((item) => item.field === 'role_id')
        item.option = this.roleList.map((item) => {
          return {
            value: item.id,
            label: item.name
          }
        })
      })
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      let info = { pageNumber: this.pageNumber, pageSize: this.pageSize }
      info = Object.assign(info, this.searchParams)
      apiUsers(info)
        .then((res) => {
          const { data, total } = res
          this.dataList = data
          this.pageTotal = total
          this.dataListLoading = false
          this.$refs.table.doLayout()
        })
        .catch((e) => {
          this.dataList = []
          this.pageTotal = 0
          this.dataListLoading = false
        })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageNumber = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNumber = val
      this.getDataList()
    },
    // 列表查询
    searchParma(e) {
      this.searchFormArr.forEach((item) => {
        if (e[item.field]) {
          this.searchParams[item.field] = e[item.field]
        } else {
          this.searchParams[item.field] = ''
        }
      })
      if (e.dept_id && e.dept_id.length > 0) {
        this.searchParams.dept_id = e.dept_id[e.dept_id.length - 1]
      } else {
        this.searchParams.dept_id = ''
      }
      this.pageNumber = 1
      this.getDataList()
    },
    // 添加
    handleAdd() {
      this.editModel = 'add'
      this.showDialogAdd = true
    },
    // 以其身份登录
    handleLogin(scope) {
      this.dataListLoading = true
      this.$store
        .dispatch('user/otherUserlogin', scope.row.id)
        .then(() => {
          location.href = '/'
          this.dataListLoading = false
        })
        .catch(() => {
          this.dataListLoading = false
        })
    },
    // 编辑
    handleEdit(scope) {
      this.editModel = 'edit'
      this.currentItem = scope.row
      this.showDialogAdd = true
    },
    handleDeleteMultiple() {
      this.handleDelete(this.multipleSelection.map((item) => item.id))
    },
    // 删除
    handleDelete(ids) {
      window.enterPreventDefault = false
      this.$confirm('确定要删除这个账号？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          window.enterPreventDefault = true
          this.dataListLoading = true
          apiUserDel({ ids })
            .then((res) => {
              this.dataListLoading = false
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.getDataList()
            })
            .catch(() => {
              this.dataListLoading = false
            })
        })
        .catch(() => {
          window.enterPreventDefault = true
        })
    },
    // 添加成功
    handleAddSuccess() {
      this.showDialogAdd = false
      this.getDataList()
    },
    // 表格多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleOn() {
      apiSysUserSts({
        status: 1,
        ids: this.multipleSelection.map((item) => item.id)
      }).then((res) => {
        this.$message({
          type: 'success',
          message: '启用成功'
        })
        this.getDataList()
      })
    },
    handleOff() {
      apiSysUserSts({
        status: 0,
        ids: this.multipleSelection.map((item) => item.id)
      }).then((res) => {
        this.$message({
          type: 'success',
          message: '停用成功'
        })
        this.getDataList()
      })
    },
    selectable(row, index) {
      if (row.account === 'admin') {
        return false
      } else {
        return true
      }
    },
    getListName(list, id) {
      return getListName(list, id)
    }
  }
}
</script>
